package com.example.redis.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.redis.demo.dto.UserLoginDTO;
import com.example.redis.demo.exception.BusinessException;
import com.example.redis.demo.mapper.UserLoginLogMapper;
import com.example.redis.demo.mapper.UserMapper;
import com.example.redis.demo.model.User;
import com.example.redis.demo.model.UserLoginLog;
import com.example.redis.demo.service.RabbitMqService;
import com.example.redis.demo.util.JsonUtil;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class RabbitMqServiceImpl implements RabbitMqService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserLoginLogMapper userLoginLogMapper;

    @Override
    @RabbitListener(queues = {"login"})
    public void onUserLogin(Message message, Channel channel) {
        String messageBody = new String(message.getBody());
        UserLoginDTO userLoginDTO = JsonUtil.parseObject(messageBody, UserLoginDTO.class);
        //4. 完善last_login_time字段
        LambdaUpdateWrapper<User> userLambdaUpdateWrapper = new UpdateWrapper<User>().lambda();
        userLambdaUpdateWrapper.set(User::getLastLoginTime, new Date());
        userLambdaUpdateWrapper.set(User::getUpdateTime, new Date());
        userLambdaUpdateWrapper.set(User::getUpdateUser, userLoginDTO.getUserName());
        userLambdaUpdateWrapper.eq(User::getId, userLoginDTO.getUserId());
        this.userMapper.update(null, userLambdaUpdateWrapper);
        //5.写登录记录表
        final UserLoginLog loginLog = new UserLoginLog();
        loginLog.setLongitude(userLoginDTO.getLongitude());
        loginLog.setLatitude(userLoginDTO.getLatitude());
        loginLog.setUserId(userLoginDTO.getUserId());
        loginLog.setCreateTime(new Date());
        loginLog.setCreateUser(userLoginDTO.getUserName());
        loginLog.setIsDeleted(0);
        int logRes = userLoginLogMapper.insert(loginLog);
        if (logRes < 1) {
            throw BusinessException.errorOfCode("写入登录日志失败", "500");
        }

    }
}
